找传奇、传世资源到传世资源站!

java 音乐播放器 示例源码(亲测可用)

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

有图形用户界面、能根据本地路径导入本地音乐,项目中含jmf相关 jar包下载from clipboard
from clipboard
import java.io.*;//import java.applet.AudioClip;import java.awt.BorderLayout;import java.awt.Button;import java.awt.Color;import java.awt.FileDialog;import java.awt.Frame;import java.awt.GridLayout;import java.awt.Label;import java.awt.List;import java.awt.Menu;import java.awt.MenuBar;//设置图片和背景颜色import java.awt.MenuItem;import java.awt.Panel;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import javax.sound.sampled.AudioFileFormat;import javax.sound.sampled.AudioFormat;//获得音频文件中包含的音频数据的格式。import javax.sound.sampled.AudioInputStream;//通过转换提供的音频输入流,获得所指示格式的音频输入流。import javax.sound.sampled.AudioSystem;//import javax.sound.sampled.Clip;import javax.sound.sampled.DataLine;import javax.sound.sampled.SourceDataLine;import javax.sound.sampled.UnsupportedAudioFileException;import javax.swing.JOptionPane;//import com.sun.javafx.collections.MappingChange.Map;////import javazoom.jl.decoder.Manager;//import javazoom.jl.player.Player;//import javax.media.*;////import javax.media.bean.*;//import javax.management.*;//import javax.media.bean.playerbean.*;//import java.time.*;//这里是标记@SuppressWarnings("unused")public class SoundPlayerTest extends Frame{private static final long serialVersionUID = 1L;boolean isStop = true;// 控制播放线程boolean hasStop = true;// 播放线程状态String filepath;// 播放文件目录String filename;// 播放文件名称AudioInputStream audioInputStream;// 文件流AudioFormat audioFormat;// 文件格式SourceDataLine sourceDataLine;// 输出设备List list;// 文件列表Label labelfilepath;//播放目录显示标签Label labelfilename;//播放文件显示标签 Button buttonNext,buttonLast,buttonStop,showlist;//上、下一首、停止按钮,保存当前当前打开文件列表的音乐int songNum,num,i,f=0;int judge=0;//String F[]=new String[10]; public SoundPlayerTest() throws IOException {// 设置窗体属性setLayout(new BorderLayout());setTitle("音月");setSize(380,500); // 建立菜单栏MenuBar menubar = new MenuBar();Menu menufile = new Menu("菜单");MenuItem menuopen = new MenuItem("打开");MenuItem itemExit=new MenuItem("退出"); menufile.add(menuopen);menufile.addSeparator();menufile.add(itemExit);menuopen.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {try {open();} catch (IOException e1) {// TODO Auto-generated catch block//e1.printStackTrace();}}});itemExit.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) { System.exit(0);}});menubar.add(menufile);setMenuBar(menubar);// 文件列表list = new List();list.addMouseListener(new MouseAdapter() {public void mouseClicked(MouseEvent e) {// 双击时处理if (e.getClickCount() == 2) {// 播放选中的文件 filename = list.getSelectedItem(); songNum=list.getSelectedIndex();num=songNum; // System.out.printf("位置%d\n",songNum); play();}}});list.setBackground(Color.pink);add(list, "Center");// 信息显示Panel panel = new Panel(new GridLayout(0, 1));labelfilepath = new Label("正在播放:");labelfilename = new Label("播放列表");buttonLast=new Button("上一首");buttonLast.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {songNum=list.getSelectedIndex();if(songNum>0){list.select(songNum-1);filename = list.getItem(songNum-1);num=songNum-1;play();}}});//****************************************buttonStop=new Button("停止");buttonStop.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {isStop=true;labelfilepath.setText("播放停止");}});////****************************************showlist=new Button("导入");showlist.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {//歌曲显示list.removeAll();String w = "音乐路径.txt";BufferedReader in = null;try {in = new BufferedReader( new FileReader(w));} catch (FileNotFoundException e2) {// TODO Auto-generated catch block//e2.printStackTrace();} String nowid = null;try {nowid = in.readLine();} catch (IOException e2) {// TODO Auto-generated catch block//e2.printStackTrace();}labelfilepath.setText(nowid); while(nowid!=null) { //F[f]=nowid; filepath=nowid; if (filepath != null) {labelfilepath.setText("音乐路径:" filepath);File filedir = new File(filepath);File[] filelist = filedir.listFiles();//过滤该路径所在文件是wav,MP3格式的文件并在面板中显示for (File file : filelist) {String filename = file.getName().toLowerCase();if (filename.endsWith(".wav")||filename.endsWith(".mp3")) {list.add(filename);}}}//f ;try {nowid=in.readLine();} catch (IOException e1) {// TODO Auto-generated catch block//e1.printStackTrace();}} try {in.close();} catch (IOException e1) {// TODO Auto-generated catch block//e1.printStackTrace();}}});//*****************************************buttonNext=new Button("下一首");buttonNext.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {songNum=list.getSelectedIndex();if((songNum 1)<list.getItemCount()){list.select(songNum 1);filename = list.getItem(songNum 1);num=songNum 1;play();}}});buttonNext.setBackground(Color.ORANGE);buttonLast.setBackground(Color.GREEN);buttonStop.setBackground(Color.GRAY);showlist.setBackground(Color.blue);list.setBackground(Color.white);panel.add(labelfilepath);panel.add(buttonLast);panel.add(buttonStop);panel.add(buttonNext);panel.add(showlist);panel.add(labelfilename);add(panel, "North");// 注册窗体关闭事件addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}});setVisible(true);}// 打开private void open() throws IOException {FileDialog dialog = new FileDialog(this, "Open", 0);dialog.setVisible(true);boolean m=true;String w = "音乐路径.txt";BufferedReader in=new BufferedReader( new FileReader(w)); String nowid=in.readLine();filepath = dialog.getDirectory();//保存对话框的路径 while(nowid!=null) { if(nowid.equals(filepath)) { JOptionPane.showMessageDialog(null, "该路径已保存!"); //弹出提示框 m=false; break ; } nowid=in.readLine(); } if(m){RandomAccessFile randomFile = new RandomAccessFile(w, "rw"); long fileLength = randomFile.length(); //将写文件指针移到文件尾。 randomFile.seek(fileLength); randomFile.writeBytes(filepath "\r\n"); randomFile.close();} if (filepath != null) {labelfilepath.setText("音乐路径:" filepath);String song;song=filepath ".txt"; BufferedWriter out=new BufferedWriter( new FileWriter(song)); // System.out.println("新建成功标记");// 显示文件列表File filedir = new File(filepath);File[] filelist = filedir.listFiles();//过滤该路径所在文件是wav,MP3格式的文件并在面板中显示for (File file : filelist) {String filename = file.getName().toLowerCase();if (filename.endsWith(".wav")||filename.endsWith(".mp3")) {list.add(filename);out.write(filename); out.newLine();}}out.close();}}// 播放private void play() {try {isStop = true;// 停止播放线程// 等待播放线程停止//System.out.print("开始播放:" filename);while (!hasStop) {//System.out.print(".");try {Thread.sleep(10);} catch (Exception e) {}}//System.out.println("");//进行路径的选择判断 String flag=null; String M[]=new String[5]; int m=0;String w = "音乐路径.txt";BufferedReader in=new BufferedReader( new FileReader(w)); String nowid=in.readLine(); while(nowid!=null) { M[m]=nowid; nowid=in.readLine(); m ; } in.close(); for(int i=0;i<m;i ) { String ww = M[i] ".txt"; BufferedReader nn=new BufferedReader( new FileReader(ww)); String nowd=nn.readLine(); while(nowd!=null) { if( nowd.equals(filename) ){ filepath =M[i]; break; } else nowd= nn.readLine(); } nn.close(); } File file = new File(filepath filename); //文件长度 long minute = 0,second = 0;long total = 0;try {AudioFileFormat aff = AudioSystem.getAudioFileFormat(file);java.util.Map<String, Object> props = aff.properties();if (props.containsKey("duration"))total = (long) Math.round((((Long) props.get("duration")).longValue())/1000);//System.out.println("这里显示的是播放的时长\n");minute=total/60000;second=total/1000-minute*60;} catch (UnsupportedAudioFileException e) {// TODO Auto-generated catch block//e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch block//e.printStackTrace();} labelfilepath.setText("正在播放:" filename " " "共时长" minute "分 " second "秒"); // 取得文件输入流audioInputStream = AudioSystem.getAudioInputStream(file);audioFormat = audioInputStream.getFormat();// 转换wav文件编码if (audioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,audioFormat.getSampleRate(), 16, audioFormat.getChannels(), audioFormat.getChannels() * 2,audioFormat.getSampleRate(), false);audioInputStream = AudioSystem.getAudioInputStream(audioFormat,audioInputStream);}// 打开输出设备DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat,AudioSystem.NOT_SPECIFIED);sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);sourceDataLine.open(audioFormat);sourceDataLine.start();// 创建独立线程进行播放isStop = false;Thread playThread = new Thread(new PlayThread());playThread.start();//playThread.join();//System.out.printf("\n这里2是%d",judge);} catch (Exception e) {//e.printStackTrace();} }public static void main(String args[]) throws IOException {new SoundPlayerTest();}private void clcle(){ if((num 1)<list.getItemCount()){list.select(num 1);filename = list.getItem(num 1);hasStop = false; num=songNum 1;songNum=num;System.out.printf("\n这是songnum的显示位置\n%d",songNum);System.out.printf("\n这是num的显示位置\n%d",num);play();}}// 播放线程class PlayThread extends Thread {private boolean iss;byte tempBuffer[] = new byte[320];public void run() {try {int cnt;judge=0;hasStop = false;// 读取数据到缓存数据while ((cnt = audioInputStream.read(tempBuffer, 0,tempBuffer.length)) != -1) {if (isStop)break;if (cnt > 0) {// 写入缓存数据sourceDataLine.write(tempBuffer, 0, cnt);}}// Block等待临时数据被输出为空sourceDataLine.drain();sourceDataLine.close();hasStop = true;iss=true;System.out.println("1" hasStop "\n");System.out.println("iss" iss "\n");System.out.println(hasStop);if(hasStop) clcle();}catch (Exception e) {e.printStackTrace();//System.exit(0);}//finally{//if(hasStop)// clcle();// }}}}

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复